let id = 1000;
import {objectCompare}  from '../../../assets/js/objectCompare.js'
import {selectAttr} from '../../../assets/js/selectAttr.js'
export default {
    data() {
      return {
        //请求后台路径
        SRC:'',
        // 默认站展开的数据；
        defaultExpanded:[],
        moudleShow: false,
        pageShow: false,
        revampShow: false,
        pageParentCapy: 1,
        data2: [],//页面展示数据
        dataModle:[],//模块数据
        funData: [],//页面数据
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        ruleForm: {
          moudleName: '',
          moudleId: 0,
          moudleFunc: "",
          moudleIntro: ''
        },
        rules: {
          moudleName: [
            { required: true, message: '请输入模块名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20个字符', trigger: 'blur' }
          ],
          moudleFunc: [
            { required: true, message: '请输入模块标识', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20个字符', trigger: 'blur' }
          ],
          moudleId: [
            { required: true, message: 'ID不能为空'},
            { type: 'number', message: 'ID必须为数字值'}
          ]
        },
        pageForm: {
          modelId: 0,
          name: '',
          id: 0,
          description: '',
          src: ''
        },
        pages: {
          name: [
            { required: true, message: '请输入页面名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20个字符', trigger: 'blur' }
          ],
          id: [
            { required: true, message: 'ID不能为空'},
            { type: 'number', message: 'ID必须为数字值'}
          ]
        },
        revampForm: {
          revampPage:true,
          revampName: '',
          revampId: 0,
          revampIntro: '',
          revampSrc: '',
          revampModelId: '',
        },
        revampRules:{
          revampName: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20个字符', trigger: 'blur' }
          ],
          revampId: [
            { required: true, message: 'ID不能为空'},
            { type: 'number', message: 'ID必须为数字值'}
          ]
        }
      };
    },
    methods: {
      // 数据展开
      expand(data,node,store) {
        this.defaultExpanded[0] = data.name;
      },
      // 通用 成功 与 失败
      successFun(data) {
        this.$message({
          message: data,
          type: 'success'
        });
      },
      errorFun(data) {
        this.$message.error(data);
      },
      warnFun(data) {
        this.$message({
          message: data,
          type: 'warning'
        });
      },
      // 模块展示
      moudleShowFun() {
        if(this.data2.length == 0){
           this.ruleForm.moudleId = 1;
        }else{
           this.ruleForm.moudleId = this.data2[this.data2.length-1].id+1;
         }
        this.ruleForm.moudleName ='';
        this.ruleForm.moudleIntro = '';
        this.moudleShow = true;
      },
      // 添加模块
      append(store, data) {
        this.pageShow = true;
        this.pageForm.modelId = data.id;
        this.pageForm.name = "";
        // 获取最后一个子集的ID
        if(data.children.length > 0 && data.children !== undefined){
          this.pageForm.id = data.children[data.children.length-1].id+1;
        }else{
          this.pageForm.id = 1;
        }
        this.pageForm.description = '';
        this.pageForm.src = '';
        // this.pageParentCapy = this.pageForm.parentNode;
      },
      // 删除模块
      remove(store, data) {
        var id = data.id;
        var compare = function(d) {
          for(var i=0; i<d.length; i++){
            if(data.id == d[i].id){
              d.splice(i,1);
            }
          }
          return d
        }.bind(this)
        if(data.children !== undefined && data.children.length>0){
          this.warnFun("请先删除功能页面！warning！！");
        }else{
          if(data["modelId"] === undefined){
            this.$http.post(this.SRC+"model/delete.do",{id:data["id"]},{emulateJSON:true}).then(
              function(res){
                if(res.body["code"] === 0){
                 this.successFun("删除成功！");
                 compare(this.data2)
                }else{
                 this.errorFun("删除失败");
                }
              }
            )
          }else{
            this.$http.post(this.SRC+"function/delete.do",{id:data["id"]},{emulateJSON:true}).then(
              function(res){
                if(res.body["code"] === 0){
                 this.successFun("删除成功！");
                 this.getProjectData();
                }else{
                 this.errorFun("删除失败");
                }
              }
            )
          }
        }
        // store.remove(data);
      },
      // 修改模块
      revamp(store, data){
        if(data["modelId"] !== undefined){
          this.revampForm.revampPage = true;
        }else{
          this.revampForm.revampPage = false;
          this.defaultExpanded=[];
        }
        this.revampShow = true;
        this.revampForm.revampId = data.id; 
        this.revampForm.revampName = data.name;
        this.revampForm.revampIntro = data.description;
        this.revampForm.revampSrc = data.src;
        this.revampForm.revampModelId = data.modelId;
      },
      // 渲染
      renderContent(h, { node, data, store }) {
        if(data["modelId"] === undefined){
          return (
          <span>
            <span>
              <span class="el-tag">{node.label}</span>
            </span>
            <span class = 'el-tag el-tag--primary' style="margin-left: 10px;">模块标识：{data.id}</span>
            <span class = 'el-tag el-tag--primary' style="margin-left: 10px;">模块描述：{data.description}</span>
            <span style="float: right; margin-right: 20px">
              <el-button size="mini" type="info" on-click={ () => this.append(store, data) }>添加页面</el-button>
              <el-button size="mini" type="warning" on-click={ () => this.revamp(store, data) }>修改</el-button>
              <el-button size="mini" type="danger" on-click={ () => this.remove(store, data) }>删除</el-button>
            </span>
          </span>);
        }else{
          return (
          <span>
            <span>
              <span class="el-tag el-tag--gray">{node.label}</span>
            </span>
            <span class="el-tag el-tag--success" style="margin-left: 10px;">页面标识：{data.id}</span>
            <span class="el-tag el-tag--success" style="margin-left: 10px;">页面SRC：{data.src}</span>
            <span class="el-tag el-tag--success" style="margin-left: 10px;">页面描述：{data.description}</span>
            <span style="float: right; margin-right: 20px">
              <el-button size="mini" type="warning" on-click={ () => this.revamp(store, data) }>修改</el-button>
              <el-button size="mini" type="danger" on-click={ () => this.remove(store, data) }>删除</el-button>
            </span>
          </span>);
        }
        
      },
      // 模块提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var obj = {};
            obj.id = this.ruleForm.moudleId;
            obj.name = this.ruleForm.moudleName;
            obj.description = this.ruleForm.moudleIntro;
            this.data2.push(obj)
            this.$http.post(this.SRC+"model/add.do",obj,{emulateJSON:true}).then(
              function(res){
                if(res.body["code"] === 0){
                  this.successFun(res.body["msg"]);
                }else{
                  this.errorFun(res.body['msg']);
                }
              }
            );
            this.data2 = objectCompare(this.data2,"id")// 排序
          } else {
            return false;
          }
        });
      },
      // 模块重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 页面提交
      pageSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var obj = {
              modelId: this.pageForm.modelId,
              name: this.pageForm.name,
              id: this.pageForm.id,
              description: this.pageForm.description,
              src: this.pageForm.src
            }
            var moudleIndex = selectAttr(this.data2,obj.modelId,"id");//获取索引
            this.$http.post(this.SRC+'function/add.do',obj,{emulateJSON:true}).then(
              function(res){
                if(res.body["code"] === 0){
                  this.successFun("添加成功！");
                  this.getProjectData();
                }else{
                  this.errorFun(res.body['msg'])
                }
              }
            )
            this.data2 = objectCompare(this.data2,"id")// 排序
          } else {
            alert('error submit!!');
            return false;
          }
        });
      },
      // 页面重置
      resetPage(formName) {
        this.$refs[formName].resetFields();
        this.pageForm.parentNode = this.pageParentCapy;
      },
      // 修改
      revampSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var  id = this.revampForm.revampId;
            var  name = this.revampForm.revampName;
            var  intro = this.revampForm.revampIntro;
            var  modelId = this.revampForm.revampModelId;
            var  src = this.revampForm.revampSrc;
            if(this.revampForm.revampPage===true){
              let  moudleIndex = selectAttr(this.data2,modelId,"moudlId");//获取索引
              let  pageIndex = selectAttr(this.data2[moudleIndex].children,id);//获取索引
              let  d = this.data2[moudleIndex].children[pageIndex];
              d.id = id;
              d.name = name;
              d.modelId = modelId;
              d.src = src;
              d.description = intro;
              this.$http.post(this.SRC+"function/modify.do",d,{emulateJSON:true}).then(
                function(res){
                  if(res.body["code"] === 0){
                    this.successFun("修改成功！");
                    this.getProjectData();
                  }else{
                    this.errorFun(res.body['msg']);
                  }
                })
            }else{
              let  moudleIndex = selectAttr(this.data2,id,"id");//获取索引
              let  d = this.data2[moudleIndex];
              d.id = id;
              d.name = name ;
              d.description = intro;
              this.$http.post(this.SRC+"model/modify.do",d,{emulateJSON:true}).then(
                function(res){
                  if(res.body["code"] === 0){
                    this.successFun("修改成功！");
                  }else{
                    this.errorFun(res.body['msg']);
                  }
                })
            }
            this.data2 = objectCompare(this.data2,"id")// 排序
          } else {
            alert('error submit!!');
            return false;
          }
        });
      },
      // 页面重置
      resetRevamp(formName) {
        this.$refs[formName].resetFields();
        this.revampForm.revampModelId = 0;
        this.revampForm.revampSrc = '';
      },
      //获取后台数据
      getProjectData(){
        var that = this;
        function post(url){
          return new Promise(
            function(resolve,reject){
              that.$http.post(that.SRC+url).then(
                function(res){
                  if(res.body['code'] === 0){
                    resolve(res.body['msg']);
                  }else{
                    reject(false);
                  }
                }
              )
            }
          )
        }
        var urlData = ["function/list.do","/model/list.do"]
        function renderAll() {
          return Promise.all([post(urlData[0]), post(urlData[1])]);
        }
        renderAll().then(function(value){
          that.funData = value[0];
          that.dataModle = value[1]
          for(var i = 0; i<value[1].length; i++){
            value[1][i].children = [];
            for(var j = 0; j<value[0].length; j++){
              if(value[1][i]['id'] == value[0][j]['modelId']){
                value[1][i].children.push(value[0][j])
              }
            }
          }
          that.data2 = value[1];
        })
      }
    },
    mounted() {
      this.SRC = this.$store.getters.src
      this.getProjectData();
    }
}